<?php include "../db/db_connect.php"; ?>

<?php
    $username = trim($_POST["username"]);

    function createRandomPassword() {
	    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        srand((double)microtime()*1000000);

        $i = 0;
        $pass = '' ;

        while ($i <= 8) {
            $num = rand() % 61;
            $tmp = substr($chars, $num, 1);
            $pass = $pass . $tmp;
            $i++;
        }

        return $pass;
    }

    $raw_password = createRandomPassword();
    $password = md5($raw_password);
    
    $qry = "update user set user_password=\"{$password}\" where user_name=\"{$username}\"";
    echo $qry;
	if (!mysql_query($qry, $con)) {
		echo "update user password failed";
	}
?>

<?php include "../db/db_close.php"; ?>

<?php include "../mail/mail.php"; ?>

<?php
    $mail->AddAddress($username, $username);
    $mail->Subject = "You have reset your password for TestSmart";
    $mail->Body    = "This mail is generated automatically, do not reply.<br />Your new password is " . $raw_password;
 
    if(!$mail->Send()) {
        echo "Message could not be sent. <p>";
        echo "Mailer Error: " . $mail->ErrorInfo;
        exit;
    }
 
    header("Location: ../../login.php");
?>